package corej.course.collection.list.arraylist;

public class TestMyList {
    public static void main(String[] args) {
        MyList list = new MyList();
        list.add("abc");
        list.add("def");
        list.add("ghi");
        list.add("jkl");
        list.add("abc");
        list.add(0, "123");
        list.remove(2);

        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            System.out.println(o);
        }
    }
}

class MyList {
    private Object[] data = new Object[3];

    private int index = 0;

    private void expand() {
        Object[] data2 = new Object[data.length * 2];
        System.arraycopy(data, 0, data2, 0, data.length);
        data = data2;
    }

    public void add(Object o) {
        if (data.length == index)
            expand();
        data[index] = o;
        index++;
    }

    public void add(int pos, Object o) {
        if (data.length == index)
            expand();
        for (int i = index; i > pos; i--) {
            data[i] = data[i - 1];
        }
        data[pos] = o;
        index++;
    }

    public Object remove(int pos) {
        Object o = data[pos];
        index--;
        for (int i = pos; i < index; i++) {
            data[i] = data[i + 1];
        }
        return o;
    }

    public int size() {
        return index;
    }

    public Object get(int pos) {
        return data[pos];
    }

    public void clear() {
        index = 0;
    }

    public boolean isEmpty() {
        return index == 0;
    }

    public Object[] toArray() {
        return data;
    }
}
